package com.nuvsoft.android.nuvgamenet.example.buzzer.activities;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.nuvsoft.android.nuvgamenet.NuvGameNetApplication;
import com.nuvsoft.android.nuvgamenet.R;
import com.nuvsoft.android.nuvgamenet.example.buzzer.BuzzerApplication;
import com.nuvsoft.android.nuvgamenet.example.buzzer.BuzzerNetSignals;
import com.nuvsoft.android.nuvgamenet.net.TCPListener;
import com.nuvsoft.android.nuvgamenet.net.TCPHandler.TCPConnection;

public class BuzzerGame extends Activity {
	public BuzzerApplication ba;
	public boolean isHost;
	public Random rand;

	public int currentAnswer;

	private RadioGroup rg;
	private RadioButton rb_a1, rb_a2, rb_a3, rb_a4;
	private Button b_buzzer;
	private TextView tv_question;

	private Handler uiHandler;

	private volatile boolean questionAnswered;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_room);
		ba = (BuzzerApplication) getApplication();
		rand = new Random(System.currentTimeMillis());
		isHost = ba.getConnectionManager().getTCPHandler().isHost();
		uiHandler = new Handler();
	}

	private void setupQuestion(String question, String a1, String a2,
			String a3, String a4) {
		tv_question.setText(question);

		rb_a1.setText(a1);
		rb_a1.setSelected(false);

		rb_a2.setText(a2);
		rb_a2.setSelected(false);

		rb_a3.setText(a3);
		rb_a3.setSelected(false);

		rb_a4.setText(a4);
		rb_a4.setSelected(false);

		setEnableAll(true);
	}

	public void setEnableAll(boolean value) {
		b_buzzer.setEnabled(value);
		rb_a1.setEnabled(value);
		rb_a2.setEnabled(value);
		rb_a3.setEnabled(value);
		rb_a4.setEnabled(value);
	}

	public void onStart() {
		super.onStart();
		tv_question = (TextView) findViewById(R.id.tv_question);
		b_buzzer = (Button) findViewById(R.id.b_answer);

		// setup button action
		b_buzzer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (rg.getCheckedRadioButtonId() > -1) {
					final int answer = Integer
							.parseInt(((RadioButton) findViewById(rg
									.getCheckedRadioButtonId())).getText()
									.toString());
					if (isHost) {
						if (answer == currentAnswer) {
							ba.getConnectionManager().getTCPHandler()
									.sendToAll(
											BuzzerNetSignals.WINNER.name(),
											new String[] {
													NuvGameNetApplication
															.getNick(),
													String.valueOf(answer) });
							uiHandler.post(new Runnable() {
								public void run() {
									showWinner(BuzzerApplication.getNick(), String
											.valueOf(currentAnswer));
								}
							});
						}
					} else {
						ba.getConnectionManager().currentHost.send(
								BuzzerNetSignals.ANSWER.name(),
								new String[] { String.valueOf(answer) });
					}
					setEnableAll(false);
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					setEnableAll(true);
				}
			}
		});

		rb_a4 = (RadioButton) findViewById(R.id.rb_a4);
		rb_a1 = (RadioButton) findViewById(R.id.rb_a1);
		rb_a2 = (RadioButton) findViewById(R.id.rb_a2);
		rb_a3 = (RadioButton) findViewById(R.id.rb_a3);
		rg = (RadioGroup) findViewById(R.id.rg_answers);

		// add broadcast listeners
		if (isHost) {
			ba.getConnectionManager().getTCPHandler().addTCPListener(
					new TCPListener() {
						@Override
						public void onReceiveUnverfied(TCPConnection t,
								String tag, String[] data) {
						}

						@Override
						public void onReceiveVerified(TCPConnection t,
								String tag, String[] data) {
							if (tag.equalsIgnoreCase(BuzzerNetSignals.ANSWER
									.name())) {
								String answer = data[0];
								if (checkAnswer(answer)) {
									String nick = t.getPlayerInfo().getNick();
									ba
											.getConnectionManager()
											.getTCPHandler()
											.sendToAll(
													BuzzerNetSignals.WINNER
															.name(),
													new String[] { nick, answer });
									showWinner(nick, String
											.valueOf(currentAnswer));
								}
							}
						}
					});

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			ba.getConnectionManager().getTCPHandler().addTCPListener(
					new TCPListener() {
						@Override
						public void onReceiveUnverfied(TCPConnection t,
								String tag, String[] data) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onReceiveVerified(TCPConnection t,
								String tag, final String[] data) {
							if (tag
									.equalsIgnoreCase(BuzzerNetSignals.NEW_QUESTION
											.name())) {
								uiHandler.post(new Runnable() {
									@Override
									public void run() {
										setupQuestion(data[0], data[1],
												data[2], data[3], data[4]);
									}
								});
							} else if (tag
									.equalsIgnoreCase(BuzzerNetSignals.WINNER
											.name())) {
								uiHandler.post(new Runnable() {
									public void run() {
										showWinner(data[0], data[1]);
									}
								});
							}
						}

					});
		}

		// start the game
		if (isHost) {
			generateQA();
		}
	}

	private void showWinner(final String nick, final String answer) {
		this.uiHandler.post(new Runnable() {
			@Override
			public void run() {
				tv_question.setText(String.format("%s answered first! (%s)",
						nick, answer));
				setEnableAll(false);
				if (isHost) {
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								Thread.sleep(5000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							generateQA();
						}
					}).start();
				}
			}
		});
	}

	public boolean checkAnswer(String a) {
		if (!questionAnswered && Integer.parseInt(a) == currentAnswer) {
			questionAnswered = true;
			return true;
		} else {
			return false;
		}
	}

	public void generateQA() {
		final int first = rand.nextInt(9) + 1;
		final int second = rand.nextInt(9) + 1;
		currentAnswer = first * second;
		List<Integer> answer = new LinkedList<Integer>();
		answer.add(first * second);
		answer.add((first + 1) * second);
		answer.add(first * (second + 1));
		answer.add((first + 1) * (second + 1));
		answer.add((first - 1) * second);
		answer.add(first * (second - 1));
		answer.add((first - 1) * (second - 1));
		Collections.shuffle(answer);

		do {
			int index = rand.nextInt(answer.size());
			if (answer.get(index) != currentAnswer)
				answer.remove(index);
		} while (answer.size() > 4);

		ba.getConnectionManager().getTCPHandler().sendToAll(
				BuzzerNetSignals.NEW_QUESTION.name(),
				new String[] { String.format("%d * %d = ?", first, second),
						String.valueOf(answer.get(0)),
						String.valueOf(answer.get(1)),
						String.valueOf(answer.get(2)),
						String.valueOf(answer.get(3)) });

		final Object[] answers = answer.toArray();

		uiHandler.post(new Runnable() {
			public void run() {
				setupQuestion(String.format("%d * %d = ?", first, second),
						String.valueOf((Integer) answers[0]), String
								.valueOf((Integer) answers[1]), String
								.valueOf((Integer) answers[2]), String
								.valueOf((Integer) answers[3]));
			}
		});

		questionAnswered = false;
	}
}
